<template>
  <view class="cart-page">
    <!-- 借书车头部 -->
    <view class="cart-header" v-if="list.length > 0">
      <view class="select-all">
        <checkbox-group @change="handleSelectAll">
          <checkbox :checked="allSelected" color="#3E88F0" />
          <text class="select-text">全选</text>
        </checkbox-group>
      </view>
      <text class="cart-count">共 {{ list.length }} 本图书</text>
    </view>

    <!-- 借书车列表 -->
    <view v-if="list.length === 0" class="empty">
      <text class="empty-text">借书车为空</text>
      <text class="empty-tip">去首页逛逛，加入喜欢的图书吧~</text>
      <button class="btn-go-home" @click="goHome">去首页</button>
    </view>
    <view v-else class="cart-list">
      <view class="cart-item" v-for="item in list" :key="item.id">
        <checkbox-group @change="handleItemSelect(item.id)">
          <checkbox :checked="selectedIds.includes(item.id)" color="#3E88F0" />
        </checkbox-group>
        <image 
          :src="item.cover || '/static/img/default-avatar.png'" 
          class="cover" 
          mode="aspectFill"
        ></image>
        <view class="info">
          <text class="name">{{ item.name }}</text>
          <text class="author">{{ item.author }}</text>
          <text class="days">借阅天数：{{ item.borrowDays }} 天</text>
        </view>
        <button class="btn-remove" @click="removeItem(item.id)">移除</button>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="cart-footer" v-if="list.length > 0">
      <view class="selected-info">
        <text class="selected-count">已选 {{ selectedIds.length }} 本</text>
      </view>
      <button 
        class="btn-borrow" 
        :disabled="selectedIds.length === 0 || borrowing"
        @click="handleBatchBorrow"
      >
        {{ borrowing ? '借阅中...' : '立即借阅' }}
      </button>
    </view>
  </view>
</template>

<script>
import { myRequest } from '@/util/request.js';

export default {
  name: 'Cart',
  data() {
    return {
      list: [],
      selectedIds: [], // 选中的图书ID
      allSelected: false,
      borrowing: false
    };
  },
  onShow() {
    this.fetchList();
  },
  methods: {
    async fetchList() {
      try {
        const data = await myRequest({ url: '/api/cart', method: 'GET' });
        this.list = Array.isArray(data) ? data : [];
        this.selectedIds = [];
        this.allSelected = false;
      } catch (e) {
        console.error('获取借书车失败', e);
      }
    },

    // 移除图书
    async removeItem(id) {
      uni.showModal({
        title: '提示',
        content: '确定要移除这本图书吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await myRequest({ url: `/api/cart/${id}`, method: 'DELETE' });
              uni.showToast({ title: '已移除', icon: 'success' });
              this.fetchList();
            } catch (e) {
              console.error('移除失败', e);
            }
          }
        }
      });
    },

    // 全选/取消全选
    handleSelectAll(e) {
      if (e.detail.value.length > 0) {
        this.selectedIds = this.list.map(item => item.id);
        this.allSelected = true;
      } else {
        this.selectedIds = [];
        this.allSelected = false;
      }
    },

    // 单选
    handleItemSelect(id) {
      const index = this.selectedIds.indexOf(id);
      if (index > -1) {
        this.selectedIds.splice(index, 1);
      } else {
        this.selectedIds.push(id);
      }
      this.allSelected = this.selectedIds.length === this.list.length;
    },

    // 批量借阅
    async handleBatchBorrow() {
      if (this.selectedIds.length === 0) {
        uni.showToast({ title: '请选择要借阅的图书', icon: 'none' });
        return;
      }

      uni.showModal({
        title: '确认借阅',
        content: `确定要借阅选中的 ${this.selectedIds.length} 本图书吗？`,
        success: async (res) => {
          if (res.confirm) {
            this.borrowing = true;
            let successCount = 0;
            let failCount = 0;

            for (const cartId of this.selectedIds) {
              const cartItem = this.list.find(item => item.id === cartId);
              if (!cartItem) {
                console.error(`找不到购物车项目: ${cartId}`);
                failCount++;
                continue;
              }

              try {
                await myRequest({
                  url: '/api/borrow',
                  method: 'POST',
                  data: {
                    bookId: cartItem.bookId,  // 使用正确的字段名
                    borrowDays: cartItem.borrowDays || 30
                  }
                });
                successCount++;
                // 借阅成功后从借书车移除
                await myRequest({ url: `/api/cart/${cartId}`, method: 'DELETE' });
              } catch (e) {
                console.error('借阅失败', e);
                // 记录具体的错误信息
                const errorMsg = e?.message || e?.msg || '未知错误';
                console.error(`图书 ${cartItem.name || cartId} 借阅失败: ${errorMsg}`);
                failCount++;
              }
            }

            this.borrowing = false;
            
            if (successCount > 0) {
              uni.showToast({ 
                title: `成功借阅 ${successCount} 本图书`, 
                icon: 'success' 
              });
              this.fetchList();
              // 跳转到书架页面查看借阅记录
              setTimeout(() => {
                uni.switchTab({ url: '/pages/bookshelf/bookshelf' });
              }, 1500);
            }
            
            if (failCount > 0) {
              uni.showToast({ 
                title: `${failCount} 本图书借阅失败`, 
                icon: 'none' 
              });
            }
          }
        }
      });
    },

    // 去首页
    goHome() {
      uni.switchTab({ url: '/pages/index/index' });
    }
  }
}
</script>

<style scoped>
.cart-page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: #f5f5f5;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  margin-bottom: 20rpx;
}

.select-all {
  display: flex;
  align-items: center;
}

.select-text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.cart-count {
  font-size: 26rpx;
  color: #666;
}

.empty {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.empty-tip {
  font-size: 26rpx;
  color: #ccc;
  margin-bottom: 40rpx;
}

.btn-go-home {
  padding: 20rpx 60rpx;
  background: #3E88F0;
  color: #fff;
  border-radius: 40rpx;
  border: none;
}

.cart-list {
  flex: 1;
  padding: 0 20rpx 140rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.cart-item {
  display: flex;
  gap: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  align-items: center;
}

.cover {
  width: 120rpx;
  height: 160rpx;
  border-radius: 8rpx;
  background: #f5f5f5;
}

.info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.name {
  font-size: 30rpx;
  color: #333;
  font-weight: 600;
  line-height: 1.3;
}

.author {
  font-size: 26rpx;
  color: #666;
}

.days {
  font-size: 24rpx;
  color: #999;
}

.btn-remove {
  padding: 10rpx 20rpx;
  font-size: 24rpx;
  background: #fff;
  color: #ff4d4f;
  border: 1rpx solid #ff4d4f;
  border-radius: 20rpx;
}

.cart-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
}

.selected-info {
  flex: 1;
}

.selected-count {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.btn-borrow {
  padding: 20rpx 60rpx;
  background: #3E88F0;
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

.btn-borrow[disabled] {
  background: #ccc;
  color: #999;
}
</style>